<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 300px;
            height: 20px;
            border: 1px solid red;
        }
        .progress{
            width: 0%;
            height: 20px;
            background-color: red;
            transition: all .5s;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="progress"  >
         
        </div>
    </div>
    <ul id="ul">
        <!-- <li>
            <a href="#">文件名</a>
        </li> -->
    </ul>
    <script>

        var ul = document.getElementById('ul')
        var progress = document.getElementsByClassName('progress')[0];

        const bc = function(tagName) {
            return document.createElement(tagName)
        }

        function download() {
            var url = '/download?filename='+this.innerHTML
            var xhr = new XMLHttpRequest()
            xhr.open('get', url)
            xhr.send()
            xhr.onprogress = function(e) {
                console.log(e);
                
                var n = e.loaded / e.total * 100;
                progress.style.width = n + '%';
                progress.innerHTML = n.toFixed(2) + '%'
            }
            xhr.onload = function() {
                let filename = xhr.getResponseHeader('Content-Disposition');
                filename = filename.split('filename=')[1]

                if (window.chrome) {
                    // chrome
                    var a = bc('a');
                    a.href = url;
                    document.body.appendChild(a);
                    a.click();
                } if (window.navigator.msSaveBlob) {
                    // IE
                    var blob = new Blob([xhr.response], { type: 'application/force-download' });
                    window.navigator.msSaveBlob(blob, filename)
                } else {
                    // firefox 其他
                    let file = new File([xhr.response], filename, { type: 'application/force-download' });
                    window.open(URL.createObjectURL(file))
                }
            }
        }

        var xhr = new XMLHttpRequest();
        xhr.open('get', '/getFileList', true)
        xhr.send()
        xhr.onload = function() {
            var result = JSON.parse(xhr.response);
            console.log(result)

            for (var i = 0; i < result.data.length; i++) {
                var filename = result.data[i]
                var li = bc('li')
                var a = bc('a');
                a.innerHTML = filename;
                a.onclick = download
                a.href='#';
                li.appendChild(a);
                ul.appendChild(li)
            }

        }
    </script>
</body>
</html>
